package com.minelx.serverandclient.connector;

import com.minelx.serverandclient.stream.data.BytesOutput;
import com.minelx.serverandclient.stream.data.Packet;
import com.minelx.serverandclient.stream.data.StreamCache;

import java.io.IOException;
import java.io.InputStream;

import static com.minelx.serverandclient.stream.data.StreamCache.FLAG_SIZE;

public class PacketReader {

	private final InputStream source;

	private final StreamCache.Renderer renderer;

	private final BytesOutput builder;

	public PacketReader(InputStream source) {
		this.source = source;
		renderer = StreamCache.Renderer.singleton();
		builder = new BytesOutput();
	}

	public Packet take() throws IOException {
		StreamCache cache = renderer.render(source);
		while (!cache.emptyData()) {
			builder.write(cache.getCacheBytes(), FLAG_SIZE, cache.getDataLength());
			cache = renderer.render(source);
		}
		return Packet.of(builder.take());
	}
}
